#!/usr/bin/env python3
"""
telegram-bot-shadowrun
desc: A telegram bot for shadowrun. ATM only /roll with hit calc.
license: AGPL-3.0-only, see COPYING
"""


import logging
from uuid import uuid4
from telegram import Update, InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler, CallbackContext
from src import config, gen_roll

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)


def cmd_start(update: Update, context: CallbackContext) -> None:
    """Send explanation what this bot does on /start"""
    reply = """Do '/roll <number>' or '/r <number>' to roll up to 100 dice.
For source code, do /license."""
    context.bot.send_message(chat_id=update.effective_chat.id, text=reply)

def cmd_license(update: Update, context: CallbackContext) -> None:
    """Send message with license and link to source code"""
    reply = """This bot is free software under the AGPLv3.
Source: https://notabug.org/samtinel/telegram-bot-shadowrun"""
    context.bot.send_message(chat_id=update.effective_chat.id, text=reply)

def cmd_roll(update: Update, context: CallbackContext) -> None:
    """Replies with a message containing a roll with the amount of dice in the first argument"""
    reply = gen_roll.create_roll_reply(context.args)
    context.bot.send_message(chat_id=update.effective_chat.id, text=reply)

def cmd_roll_inline(update: Update, context: CallbackContext) -> None:
    """Same as roll() but inline"""
    amount = update.inline_query.query
    amount = amount.split()
    reply = gen_roll.create_roll_reply(amount)
    results = [InlineQueryResultArticle(
            id=uuid4(),
            title="Roll",
            input_message_content=InputTextMessageContent(
                reply
            ),
    )]
    update.inline_query.answer(results)

def main():
    """Start the bot. This should only be done from the parent script ../telegram-bot-shadowrun"""
    # set up bot
    updater = Updater(token=config.TOKEN, use_context=True)

    # set up handlers
    handlers = []
    handlers.append(CommandHandler('start', cmd_start))
    handlers.append(CommandHandler('license', cmd_license))
    handlers.append(CommandHandler('roll', cmd_roll))
    handlers.append(CommandHandler('r', cmd_roll))
    handlers.append(InlineQueryHandler(cmd_roll_inline))

    for handler in handlers:
        updater.dispatcher.add_handler(handler)

    # start polling
    updater.start_polling()
